<template>
  <a-card>
    <div v-if="mod=='normal'" class="account">
      <a-space class="operator">
        <a-button @click="addNew" type="primary" v-auth="`add`">新建</a-button>
        <!-- <a-button @click="addNewQianchuan" type="primary" v-auth="`add`">千川授权</a-button> -->
        <a-button @click="showSetYHS = true" type="primary" v-auth="`edit`">批量设置优化师</a-button>
        <a-select v-model="youhuashiId" style="width:120px;" @change="selectYouhuashi">
          <a-select-option :value="0">全部</a-select-option>
          <a-select-option :value="item.id" v-for="(item,index) in youhuashi" :key="index" >
            {{item.username}}
          </a-select-option>
        </a-select>
      </a-space>
      <standard-table
        rowKey="id"
        :loading='loading'
        :columns="columns"  
        :dataSource="dataSource"
        :expandedRowKeys.sync='expandedRowKeys'
        @clear="onClear" 
        @change="onChange"
        :pagination="false" 
        @onExpand="onExpand" 
        :scroll="{x:600}"
      >
        <div slot="type" slot-scope="{record}" v-if="record.pid != 0">
          {{ record.type | setType }}
        </div>
        <div slot="account" slot-scope="{record}" >
          <a v-if="record.pid != 0 && record.ucid" target="_blank" :href="'https://shoppingads.baidu.com/shop/manageCenter/dashboard/campaignList/target/0/user/' + record.ucid">
            {{ record.account}}
          </a>
          <span v-else>
            {{ record.account}}
          </span>
        </div>
        <div slot="product_name" slot-scope="{record}" v-if="record.pid != 0" >
          {{ record.product_name }}
        </div>
        <div slot="main_product_name" slot-scope="{record}" v-if="record.pid != 0" >
          {{ record.main_product_name ? record.main_product_name : ''}}
        </div>
        <div slot="action" slot-scope="{record}" >
          <a style="margin-right: 8px" v-if="record.pid > 0" @click="goETrade(record.id,record.account)" href="javascript:;" >
            <a-icon type="reddit" />电商推广
          </a>
          <!-- <a style="margin-right: 8px" v-if="record.pid > 0" @click="getInfo(record.account)" href="javascript:;" >
            <a-icon type="dot-chart" />电商账户信息
          </a> -->
          <!-- <a style="margin-right: 8px" v-if="record.pid > 0" @click="goXinxiliu(record.id,record.account)" href="javascript:;">
            <a-icon type="pie-chart" />信息流推广
          </a> -->
          <a style="margin-right: 8px" @click="edit(record.id)" href="javascript:;" v-auth="`edit`">
            <a-icon type="edit"/>编辑
          </a>
          <a-popconfirm title="确定删除？" ok-text="删除" cancel-text="取消" @confirm='deleteRecord(record.id)' v-auth="`delete`">
            <a href="javascript:;">
              <a-icon type="delete" />删除
            </a>
          </a-popconfirm>
        </div>
      </standard-table>
    </div>
    <div v-if="mod=='add'">
      <accountAdd :mod.sync="mod" :id="detail_id" />
    </div>
    <div v-if="mod=='addQianchuan'">
      <qianchuanAdd :mod.sync="mod" :id="detail_id" />
    </div>
    <div v-if="mod=='edit'">
      <accountEdit :mod.sync="mod" :id="detail_id"/>
    </div>
    <setYouhuashi :show.sync="showSetYHS" />
    <accountData :userName="accountName" :show.sync="accountInfoShow" />
  </a-card>
</template>

<script>
import {getAllBdAccountList,delBdAccount,getOptimizerList} from '@/api/xinxiliu/account'
import StandardTable from '@/components/table/StandardTable'
// import {delUser} from '@/api/modules/setting'
import {accountAdd,accountEdit,setYouhuashi,accountData,qianchuanAdd} from './account_detail'

export default {
  name: 'account',
  components: {StandardTable,accountAdd,accountEdit,setYouhuashi,accountData,qianchuanAdd},
  data () {
    return {
      mod:'normal',

      selectedRowKeys:[],
      advanced: true,
      columns: [],
      selectedRows: [],
      loading:false,

      showSetYHS:false,

      count:0,
      limit:99999,
      page:1,
      dataSource: [],
      childArr:[],
      youhuashiId:0,
      youhuashi:[], // 优化师列表

      detail_id:0,
      expandedRowKeys:[],
      timeOut:null,
      rowKeyArray:[], //用于做屏内展示，防止打开子列表卡顿

      accountName: '',
      accountInfoShow:false,
    }
  },
  created() {
    this.init()
  },
  mounted(){
  },
  methods: {
    init(){
      this.getUserData()
      this.getOptimizerList()
      this.columns = [ 
        {
          title: 'ID',
          dataIndex: 'id',
          width: 200,
        },
        {
          title: '账户名',
          dataIndex: 'account',
          scopedSlots: { customRender: 'account' },
          width: 250,
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: 150,
        },
        {
          title: '商品名',
          dataIndex: 'product_name',
          scopedSlots: { customRender: 'product_name' },
          width: 150,
        },
        {
          title: '类型',
          dataIndex: 'type',
          scopedSlots: { customRender: 'type' },
          width: 100,
        },
        {
          title: '优化师',
          dataIndex: 'username',
          width: 150,
        },
        {
          title: '主推产品',
          dataIndex: 'main_product_name',
          scopedSlots: { customRender: 'main_product_name' },
          width: 150,
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 260,
          scopedSlots: { customRender: 'action' },
        }
      ]
    },
    getUserData(){
      const _this = this;
      this.loading = true;
      let params = {
        page:_this.page,
        limit:_this.limit
      }
      if(this.youhuashiId != 0){
        params['optid'] = this.youhuashiId
      }
      getAllBdAccountList(params).then((res) => {
        let arr = []
        let childArr = {}
        let expandedRowKeys = []
        for(let i of res.data){
          if(i.pid == 0){
            let f = res.data.filter(o=>o.pid == i.id)
            if(f.length > 0){
              childArr[i.id] = f
              i.children = []
              // i.children = f
            }
            arr.push(i)
            expandedRowKeys.push(i.id)
          }
        }
        _this.dataSource = arr
        _this.childArr = childArr
        _this.count = res.count
        _this.expandedRowKeys = []
        _this.rowKeyArray = this.dataSource.map(e=>e.id)
        _this.loading = false;
      });
    },
    getOptimizerList(){
      // 获取优化师列表
      getOptimizerList({}).then((res) => {
        if(res.errcode == 0){
          this.youhuashi = res.data
        }
      });
    },
    edit(id){
      this.detail_id = id
      this.mod = 'edit'
    },
    deleteRecord(id) {
      delBdAccount({id}).then(() => {
        this.$message.success('删除成功')
        this.init()
      });
    },
    selectYouhuashi(e){
      this.youhuashiId = e
      this.getUserData()
    },
    getChildData(row){
      // 获取子row的子children
      // row: 打开子菜单的操作时的父级row
      // console.log(row)
      let f = this.dataSource.find(e=>e.id == row.id)
      f.children = []
      let child = this.childArr[row.id]
      // let once = 30
      // const func = (current = 0) => {
      //   if (current > child.length) return;
      //   // window.requestAnimationFrame(() => {
      //   //   f.children = f.children.concat(child.slice(current, current + once))
      //   // })
      //   setTimeout(() => {
      //     f.children = f.children.concat(child.slice(current, current + once))
      //   }, 100);
      //   console.log(current + once);
      //   func(current + once)
      // }
      // func()
      
      f.children = f.children.concat(child.slice(0, 18))
      setTimeout(() => {
        f.children = f.children.concat(child.slice(18, child.length))
      },100)
    },
    getInfo(account){
      this.accountName = account
      this.accountInfoShow = true
    },
    onExpand(bool, row){
      if(bool){
        this.getChildData(row)
        this.expandedRowKeys.push(row.id)
      }else{
        row.children = []
        this.expandedRowKeys = this.expandedRowKeys.filter(e=>e !== row.id)
        // let idx = this.expandedRowKeys.findIndex(e=>e == row.id)
        // this.expandedRowKeys.splice(idx,1)
      }
      // console.log("onExpand", bool, row,this.expandedRowKeys)
    },
    selectedRowChange(selectedRowKeys, selectedRows){
      console.log('selectedRowChange',selectedRowKeys, selectedRows)
      this.selectedRowsForId = selectedRows.map(e=>e.campaignFeedId)
    },

    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    remove () {
      this.dataSource = this.dataSource.filter(item => this.selectedRows.findIndex(row => row.key === item.key) === -1)
      this.selectedRows = []
    },
    onClear() {
      this.$message.info('您清空了勾选的所有行')
    },
    onStatusTitleClick() {
      this.$message.info('你点击了状态栏表头')
    },
    onChange(e) {
      this.page = e.current
      this.init()
    },
    onSelectChange(e) {
      this.$message.info('选中行改变了',e)
    },
    addNew () {
      this.detail_id = 0
      this.mod = 'add'
    },
    addNewQianchuan() {
      this.detail_id = 2
      this.mod = 'addQianchuan'
    },
    handleMenuClick (e) {
      if (e.key === 'delete') {
        this.remove()
      }
    },
    goXinxiliu(id,name){
      this.$store.commit('dianpu/setId',{id,name})  //保存id
      this.$router.push('/xinxiliu')
    },
    goETrade(id,name){
      this.$store.commit('dianpu/setId',{id,name})  //保存id
      // this.$router.resolve('/etrade')
      let routeUrl = this.$router.resolve({
        path: "/etrade",
      });
      window.open(routeUrl.href, '_blank');
    },
  },
  watch:{
    mod(e){
      if(e=='normal'){
        this.init()
      }
    },
    showSetYHS(e){
      if(!e){
        this.getUserData()
      }
    }
  },
  filters:{
    getStatus(e){
      switch(e){
        case 1:case '1':
          return '正常'
        case 2:case '2':
          return '异常'
      }
    },
    setType(type){
      let t = ''
      switch(type){
        case 1:case '1':
          t = '商品'
          break;
        case 2:case '2':
          t = '直播'
          break;
      }
      return t
    }
  }
}
</script>

<style lang="less" scoped>
  .search{
    margin-bottom: 54px;
  }
  .fold{
    width: calc(100% - 216px);
    display: inline-block
  }
  .operator{
    margin-bottom: 18px;
  }
  @media screen and (max-width: 900px) {
    .fold {
      width: 100%;
    }
  }
</style>
